package com.example.test.service.impl;

import com.example.test.User;
import com.example.test.dao.UserRepository;
import com.example.test.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by lsl on 2021/2/24.
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean createUser(String name) {
        User newUser = User.builder()
                .name(name)
                .password("123")
                .build();
        User user = userRepository.save(newUser);
        if (redisTemplate.opsForValue().get(name) == null) {
            redisTemplate.opsForValue().set(name, user.toString());
        }
        return true;
    }

    @Override
    public List<User> queryAllUser() {
        return userRepository.findAll();
    }

    @Override
    public List<User> queryUser(User user) {
        if (user == null) {
            return Collections.emptyList();
        }
        if (user.getName() != null) {
            log.info("redis cache name: {} = value: {}", user.getName(), redisTemplate.opsForValue().get(user.getName()));
        }
        return userRepository.findAll(Example.of(user));
    }

    @Override
    public boolean updateUser(User user) {
        user.setUpdateDate(new Date());
        userRepository.saveAndFlush(user);
        return true;
    }
}
